<?php
/**
 * 物流成本基础（通用）
 * (model)
 */

namespace App\Models\MonthlyReport\Cost;
use Illuminate\Database\Eloquent\Model;
class LogisticsBasics extends Model
{
    protected $table = 'mr_cost_logistics_basics';

    protected $guarded  = [];

    public static function getLogistics($areaId,$pSkuId,$date){
        $query = self::query()->where('psku_id',$pSkuId)
            ->where('b_date',$date);
        if(is_array($areaId)){
            $query->whereIn('area_id',$areaId);
        }else{
            $query->where('area_id',$areaId);
        }
        $re = $query->first();
        if($re && $re->price){
            return $re->price;
        }else{
            $_query = self::query()->where('psku_id',$pSkuId)
                ->where('b_date','<',$date)
                ->orderBy('b_date','DESC');
            if(is_array($areaId)){
                $_query->whereIn('area_id',$areaId);
            }else{
                $_query->where('area_id',$areaId);
            }
            $re = $_query->first();
            if($re && $re->price){
                return $re->price;
            }else{
                $__query = LogisticsBalance::query()
                    ->where('psku_id',$pSkuId)
                    ->where('delivered_at','<',$date.' 00:00:00')
                    ->orderBy('delivered_at','DESC');
                if(is_array($areaId)){
                    $__query->whereIn('area_id',$areaId);
                }else{
                    $__query->where('area_id',$areaId);
                }
                $re = $__query->first();
                return $re->b_price ?? 0;
            }
        }
    }

    public static function getLastLogistics($areaId,$pSkuId){
        return self::query()->where('psku_id',$pSkuId)
            ->where('area_id',$areaId)
            ->orderBy('b_date','DESC')
            ->first();
    }

    public static function countLastLogistics($areaId,$pSkuId){
        return self::query()->where('psku_id',$pSkuId)
            ->where('area_id',$areaId)
            ->count();
    }
}
